#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time    : 2023/9/8 15:06

import json
from typing import List
import os
from typing import Any, Dict, Optional, Union
import yaml
from public_tools.files_utils.path_util import PathUtil


class YamlUtil:
    @staticmethod
    def read(file_path: str) -> Union[Dict[str, Any], Any]:
        """
        读取 yaml 文件
        :param file_path:
        :return:
        """
        file_path = PathUtil.path_sep(file_path)
        if os.path.exists(file_path):
            with open(file_path, "r", encoding="utf-8") as file:
                data = yaml.safe_load(file)
        else:
            raise FileNotFoundError(f"【读取 yaml 文件路径不存在】路径: {file_path}")
        return data

    @classmethod
    def read_config(cls, config_name: Optional[str] = None) -> Union[Dict[str, Any], Any]:
        """
        读取 config 文件
        :param config_name:
        :return:
        """
        from public_tools.common_vars import STATIC_ENV_PATH
        return cls.read(STATIC_ENV_PATH + f"{config_name}.yaml")

    @classmethod
    def read_run_config(cls, config_name: Optional[str] = None) -> Union[Dict[str, Any], Any]:
        """
        读取 config 文件
        :param config_name:
        :return:
        """
        from public_tools.common_vars import STATIC_ENV_PATH
        return cls.read(STATIC_ENV_PATH + f"{config_name}.yaml")

    @classmethod
    def write_config(cls, data, config_name="/configure"):
        from public_tools.common_vars import STATIC_ENV_PATH
        configure_path = STATIC_ENV_PATH + f"{config_name}.yaml"
        with open(configure_path, encoding="utf-8", mode="w") as f:
            yaml.dump(data, stream=f, allow_unicode=True)

    @staticmethod
    def delete_file(config_name: str):
        """
        删除指定文件
        :param config_name: 文件
        """
        from public_tools.common_vars import STATIC_ENV_PATH
        configure_path = STATIC_ENV_PATH + f"{config_name}.yaml"
        if not os.path.exists(configure_path):
            raise FileNotFoundError(f"文件 {configure_path} 不存在")

        try:
            os.remove(configure_path)
            print(f"文件 {configure_path} 已删除")
        except Exception as e:
            print(f"删除文件 {configure_path} 时出错: {e}")
class JsonUtil:
    @staticmethod
    def write_json_file(file_path: str, json_data: Union[Dict[str, Any], List[Any]]):
        """
        写入json文件
        :param file_path: 文件路径
        :param json_data: json数据
        :return:
        """
        with open(file_path, "w", encoding="utf-8") as f:
            json.dump(json_data, f, ensure_ascii=False, indent=4)

    @staticmethod
    def read_json_file(file_path: str) -> Union[Dict[str, Any], List[Any]]:
        """
        读取json文件
        :param file_path: 文件路径
        :return:
        """
        with open(file_path, "r", encoding="utf-8") as f:
            json_data = json.load(f)
        return json_data
